package xyc.sjxy.controller;

import xyc.sjxy.common.Result;
import xyc.sjxy.pojo.Users;
import xyc.sjxy.service.UserServices;
import xyc.sjxy.service.impl.UserServicesImpl;
import xyc.sjxy.servlet.BaseServlet;
import xyc.sjxy.utils.JsonUtils;
import xyc.sjxy.utils.JwtUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(urlPatterns = "/user/*")  //restfull 风格
public class UserController extends BaseServlet {
    private UserServices userServices=new UserServicesImpl();
    /**
     * 获取用户信息
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void get(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {

        //获取登录用户的token，从中解析出用户名 userName
        String token=req.getHeader("Authorization");

        //JwtUtils.validateJwt(token);
        if (token == null) {
            // 构建错误的JSON响应并直接写入响应流
            Result errorResult = Result.builder(null, 1, "请先登录", false);
            JsonUtils.WriteJson(errorResult, resp);
            // 可以考虑设置状态码为401 Unauthorized
            //resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);//设置状态码为401 Unauthorized，前端接到这个401后应该要转到登录页面（/login）
        } else {
            try {
                String username = JwtUtils.validateJwt(token);//验证token，并返回 用户名
                Users loginUser = userServices.getByUserName(username);
                Map<String, Object> map = new HashMap<>();
                map.put("userInfo", loginUser);
                JsonUtils.WriteJson(Result.builder(map, 0, "成功获取用户信息", true), resp);
            } catch (Exception e) {
                // 构建错误的JSON响应并直接写入响应流
                // e.printStackTrace();
                //resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
                System.out.println("e.getMessage() = " + e.getMessage());
                JsonUtils.WriteJson(Result.builder(null, 1, e.getMessage(), false), resp);
            }
        }
    }


    public void password(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
//更改用户密码,请求负载{old_pwd: "2214543974", new_pwd: "22145439740", re_pwd: "22145439740"}

        StringBuilder stringBuffer = new StringBuilder();
        try (BufferedReader reader = req.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuffer.append(line);
            }
        }
         Users users = JsonUtils.toObject(stringBuffer.toString(), Users.class);
        String token=req.getHeader("Authorization");
        String username = JwtUtils.validateJwt(token);//验证token，并返回 用户名
        users.setId(userServices.getByUserName(username).getId());


           if( userServices.editPwd(users)>0){
               JsonUtils.WriteJson(Result.ok(null), resp);
           }else {
               JsonUtils.WriteJson(Result.fail(null), resp);
           }





    }
    /**
     * 更新用户的头像
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */


    public void avatar(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
//更换头像
        String token=req.getHeader("Authorization");
        String username = JwtUtils.validateJwt(token);
        StringBuilder stringBuffer = new StringBuilder();
        try (BufferedReader reader = req.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuffer.append(line);
            }
        }

        Users t = JsonUtils.toObject(stringBuffer.toString(), Users.class);
        t.setId(userServices.getByUserName(username).getId());
        if(userServices.edit_pic(t)>0){
            JsonUtils.WriteJson(Result.ok(null), resp);
        }else{
            JsonUtils.WriteJson(Result.fail(null), resp);
        }

    }

    public void user(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
// 更新用户基本信息  ES6解构


        StringBuilder stringBuffer = new StringBuilder();
        try (BufferedReader reader = req.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuffer.append(line);
            }
        }
        //{"username":"test01","password":"123456","repassword":"123456"}===》Users(username,password)
        Users t = JsonUtils.toObject(stringBuffer.toString(), Users.class);

//        userServices.edit(t)>0
            if(userServices.edit(t)>0){
                JsonUtils.WriteJson(Result.ok(null), resp);
            }else{
                JsonUtils.WriteJson(Result.fail(null), resp);
            }



    }
}
